package com.powernode.config;

import com.sun.org.apache.regexp.internal.RE;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


/**
 * 写一个feign的拦截器
 * 用于token的传递
 * A---->B  这也是一次请求
 * <p>
 * token传递有三种场景
 * 1.用户正常调用
 * 浏览器----token----->A----token------>B
 * 2.mq/服务自发的调用 (需要设置一个应用token)
 * A--------->B
 * 3.其他平台回调我们的服务，在这个服务接口里面也需要调用其他服务
 * 支付宝--------->A---------->B
 */
@Component
public class FeignInterceptor implements RequestInterceptor {

    /**
     * 远程调用请求对象
     * @param template
     */
    @Override
    public void apply(RequestTemplate template) {
        // 拿到源头
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (!ObjectUtils.isEmpty(requestAttributes)){
            //1 3
            HttpServletRequest request = requestAttributes.getRequest();
            String authorization = request.getHeader("Authorization");
            if (StringUtils.hasText(authorization)){
                template.header("Authorization",authorization);
                return;
            }
        }
        //2 3 场景  需要给一个应用之间的token
        template.header("Authorization","bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJhbGwiXSwiZXhwIjozNzg2MjczMzgxLCJqdGkiOiIzZDNhOTlkMy00NjY2LTQ2NGEtYjEzMi01NWU5ODViMDFlMGYiLCJjbGllbnRfaWQiOiJwb3dlci1zaG9wIn0.HMf2yWrqbalEjupRj68LcVqBRrShGgkD7MpSyiLIj92JZrBhz8ESnAP-JQ2eikXIbExNlNXxo12jei1Ss9xQ1aqFBrDbRxnPw9UZV6KeXWjqR2JaqJlWKFS-xPz9Akpurrh3delsB50PtFPRm839VZlxB-gdgS-XqUeiORJrQM0gsnPs5cp_1IZXvZR4qNmaZq01IGS273E_DT6epgaQqfSxBb2jgg6vCZ79Scm2hht0lQflq6Z9xlLjJ4UI6L1ySc3N-9s5gafMvVfjZXrrmJthRzUm_u1nOxIunDYJ7rxG1AEfxPAHQ7xWlhrc6YyXeo4K7t0noU1Y1IKSqmbA6w");
    }
}
